package com.soc.auth.security;

import com.soc.auth.constants.RedisConstants;
import com.soc.auth.enumes.ResponseStatusEnum;
import com.soc.auth.utils.JwtUtil;
import com.soc.auth.utils.ResponseUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 用户成功登出后调用该方法
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        // 从请求头中获取jwt
        String accessToken = request.getHeader("token");
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(accessToken);
            userId = claims.getSubject();
        } catch (Exception e) {
            log.error("accessToken 过期或者格式无效");
            ResponseUtil.response(response, ResponseStatusEnum.AccessTokenError);
            // 使请求立即返回
            return;
        }

        // 从Redis中删除用户信息
        redisTemplate.delete(RedisConstants.LOGIN_USER_KEY + userId);

        ResponseUtil.response(response, ResponseStatusEnum.OK.getCode(), "用户退出登录成功");

    }
}
